package com.shopping.controller;

import com.shopping.common.Result;
import com.shopping.entity.Category;
import com.shopping.service.CategoryService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/admin/categories")
public class AdminCategoryController {

    @Resource
    private CategoryService categoryService;

    @GetMapping
    public Result<List<Category>> getCategories() {
        try {
            List<Category> categories = categoryService.list();
            return Result.success(categories);
        } catch (Exception e) {
            return Result.error("获取商品分类失败: " + e.getMessage());
        }
    }

    @PostMapping
    public Result<Boolean> addCategory(@RequestBody Category category) {
        try {
            boolean success = categoryService.save(category);
            return success ? Result.success(true) : Result.error("添加商品分类失败");
        } catch (Exception e) {
            return Result.error("添加商品分类失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public Result<Boolean> updateCategory(@PathVariable Long id, @RequestBody Category category) {
        try {
            category.setId(id);
            boolean success = categoryService.updateById(category);
            return success ? Result.success(true) : Result.error("更新商品分类失败");
        } catch (Exception e) {
            return Result.error("更新商品分类失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> deleteCategory(@PathVariable Long id) {
        try {
            boolean success = categoryService.removeById(id);
            return success ? Result.success(true) : Result.error("删除商品分类失败");
        } catch (Exception e) {
            return Result.error("删除商品分类失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}/status")
    public Result<Boolean> toggleCategoryStatus(@PathVariable Long id) {
        try {
            Category category = categoryService.getById(id);
            if (category == null) {
                return Result.error("商品分类不存在");
            }
            category.setEnabled(!category.getEnabled());
            boolean success = categoryService.updateById(category);
            return success ? Result.success(true) : Result.error("更新商品分类状态失败");
        } catch (Exception e) {
            return Result.error("更新商品分类状态失败: " + e.getMessage());
        }
    }
}